import router from "@/router"
import axios from "axios"
import { Message } from "element-ui"
import md5 from "md5";
// 密钥
import { secret } from "@/utils/secret"


const init = () => ({
    token: "", //token
    user: {
        username: "",
        attr: "",
        nickname: "",
        checkedkey: [],
    },  //用户信息

})

// 写成函数 初始时调用函数
const state = init()

const mutations = {
    // payload 传递token msg
    SET_TOKEN(state, payload = "") {
        state.token = payload
    },
    SET_USER(state, payload = {}) {
        state.user = payload
    },
    SET_USERNAMEATTR(state,payload={attr:attr,username:username}){
        state.user.attr=payload.attr
        state.user.username=payload.username
    }
}

const actions = {
    // 退出
    LOGOUT_ACTION(context) {
        context.commit("SET_TOKEN", "")
        context.commit("SET_USER", {})

        // 有可能跳转到登录页面

        setTimeout(() => {
            router.push('/login')
        }, 2000);
    },
    // 解构commit
    async LOGIN_ACTION({ commit }, payload) {
        // 发请求
        let res = await axios({
            url: "http://182.92.162.156:8083/users/login",
            method: "GET",
            params: {
                ...payload,
                password: md5(payload.password + secret)
            }
        });
        console.log(res, '登录成功');
        if (res.data.code == '1') {
            Message({
                message: '登录成功',
                type: "success"
            })
            // 登录跳转
            commit("SET_TOKEN", res.data.loginUserVo.token)
            commit("SET_USER", res.data.loginUserVo)

            //获取携带的路径
            return true

        } else {
            Message({
                message: '用户名或密码错误',
                type: "error"
            })
            return false

        }

    }
}
export default {
    // 命名空间
    namespaced: true,
    state,
    mutations,
    actions
}
